package com.reebake.ideal.message.sms.handler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.reebake.ideal.json.util.JsonUtil;
import com.reebake.ideal.message.core.MessageMediumTypeConstants;
import com.reebake.ideal.message.entity.MessageDeliveryDTO;
import com.reebake.ideal.message.entity.MessageDeliveryFeedbackDTO;
import com.reebake.ideal.message.event.MessageDeliveryEvent;
import com.reebake.ideal.message.event.MessageDeliveryFeedbackEvent;
import com.reebake.ideal.message.sms.entity.SmsSendResultDTO;
import com.reebake.ideal.message.sms.service.SmsSendService;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;

@Component
public class SmsDeliveryEventListener {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    @Autowired
    private SmsSendService smsSendService;

    @EventListener
    public void handle(MessageDeliveryEvent messageDeliveryEvent) {
        MessageDeliveryDTO messageDeliveryDTO = messageDeliveryEvent.getMessageDeliveryDTO();
        if(!MessageMediumTypeConstants.SMS.equals(messageDeliveryDTO.getMediumType())){
            return;
        }
        String channelId = messageDeliveryDTO.getChannelId();
        String outTemplateId = messageDeliveryDTO.getOutTemplateId();
        Boolean isBatchSend = messageDeliveryDTO.getIsBatchSend();
        Boolean enableDelivery = messageDeliveryDTO.getEnableDelivery();
        String phoneNumbers = messageDeliveryDTO.getReceiverIds();
        String messageHistoryId = messageDeliveryDTO.getMessageHistoryId();
        String content = messageDeliveryDTO.getContent();
        LinkedHashMap<String, String> data = new LinkedHashMap<>();
        if(StrUtil.isNotBlank(content)) {
            data = JsonUtil.toBean(content, new TypeReference<LinkedHashMap<String, String>>() {
            });
        }

        SmsSendResultDTO smsSendResultDTO = smsSendService.send(channelId, outTemplateId, phoneNumbers, data, isBatchSend, enableDelivery);

        MessageDeliveryFeedbackDTO messageDeliveryFeedbackDTO = new MessageDeliveryFeedbackDTO();
        messageDeliveryFeedbackDTO.setMessageHistoryId(messageHistoryId);
        messageDeliveryFeedbackDTO.setDeliveryTime(DateUtil.date());
        messageDeliveryFeedbackDTO.setDeliveryStatus(smsSendResultDTO.getDeliveryStatus());
        if(smsSendResultDTO.getResponseData() != null){
            messageDeliveryFeedbackDTO.setReason(smsSendResultDTO.getResponseData().toString());
        }
        applicationEventPublisher.publishEvent(new MessageDeliveryFeedbackEvent(this, messageDeliveryFeedbackDTO));
    }
}
